<?php
	/*
	* @Package functions.php
	* @author John Hamelink
	* @link http://www.syntaxmonster.net
	* @version 1.0.0
	* @since Version 1.0.0
	*/
class Functions {
	var $CI;
	
	function __construct(  ) {
		$this->CI =& get_instance(  );
		$this->CI->load->database();
		$this->CI->load->library( 'session' );
		$this->CI->load->helper( 'url' );
		$this->CI->load->library( 'typography' );
		$this->CI->load->helper( 'email' );
		$this->CI->load->helper( 'string' );
	}
	function Functions(  ) {
		self::__construct(  );
	}
	
	/**username
	* returns a capitalized version of the username
	* @return username
	*/
	function username(){
		return $this->capitalize( $this->CI->session->userdata('username') );
	}
	
		/**sitename
		* returns the sitename
		* @return sitename
		*/
	function sitename(){
		$this->CI->db->limit(1);
		$get_configuration = $this->CI->db->get("configuration");
		$configuration = $get_configuration->row_array();
		return $configuration['sitename'];
	}
		/**header_title
		* Show a suggested header based on the page currently visited
		* @param $before_text, $after_text, $delimiter
		* @return $title
		*/
	function header_title($site=null, $delimiter="|", $delimiter2="|", $before_text="", $after_text=""){
		if ($site == null){
			$this->CI->db->limit(1);
			$get_configuration = $this->CI->db->get("configuration");
			$configuration = $get_configuration->row_array();
			$site = $configuration['sitename'];
		}
		$seg_arr = $this->CI->uri->segment_array();
		if ($seg_arr == null){
			$seg_arr[]="Home";
		}
		$title = implode(" ".$delimiter2." ", $seg_arr );
		return ucwords( strtolower( $this->underscore2space($before_text .  " " . $site . " " . $delimiter . " " . $title . " " . $after_text) ) );
	}
		/**summarize
		* summarize text by a certain length of characters.
		* @param $input, $break=" ", $end_text="...", $limit=255, $tidy_html=1, $strip_html=0
		* @return $summary
		*/
	function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
		if ( strlen( $input ) >= $limit ) {
			$breakpoint = strpos( $input, $break, $limit );
			$input = substr( $input, 0, $breakpoint ) . $end_text;
		}
		if ( $tidy_html == 1 ) {
			ob_start(  );
			$tidy = new tidy;
			$config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
			$tidy->parseString( $input, $config, 'utf8' );
			$tidy->cleanRepair(  );
			$input = $tidy;
		}
		if ( $strip_html == 1 ) {
			$input = strip_tags( $input );
		}
		return $input;
	}
		/**js_add
		* Designed for modules, this function injects script tags into the header, or CDN if one is available locally
		* @param $script_url, $force_no_cdn=false
		* @return
		*/
	function js_add($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'js',$code,$admin,$main);
	}
		/**js_add_ie6
		* Designed for modules, this function injects script tags into the header, or CDN if one is available locally - only for IE6
		* @param $script_url, $force_no_cdn=false
		* @return
		*/
	function js_add_ie6($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'js-ie6',$code,$admin,$main);
	}
		/**js_add_ie7
		* Designed for modules, this function injects script tags into the header, or CDN if one is available locally - only for IE7
		* @param $script_url, $force_no_cdn=false
		* @return
		*/
	function js_add_ie7($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'js-ie7',$code,$admin,$main);
	}
		/**style_add
		* Designed for modules, this function injects stylesheet tags into the header, or CDN if one is available locally
		* @param $style_url, $force_no_cdn=false
		* @return
		*/
	function style_add($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'style',$code,$admin,$main);
	}
		/**style_add_ie6
		* Designed for modules, this function injects stylesheet tags into the header, or CDN if one is available locally - only for IE6
		* @param $style_url, $force_no_cdn=false
		* @return
		*/
	function style_add_ie6($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'style-ie6',$code,$admin,$main);
	}
		/**style_add_ie7
		* Designed for modules, this function injects stylesheet tags into the header, or CDN if one is available locally - only for IE7
		* @param $style_url, $force_no_cdn=false
		* @return
		*/
	function style_add_ie7($name,$code,$admin=0,$main=1){
		$this->_injection_add($name,'style-ie7',$code,$admin,$main);
	}
	
		/**_injection_add
		* Internal function for adding Miscellanious injections into the header
		* @return
		*/
	function _injection_add($name, $type, $code, $admin=0, $main=1){
		$data = array(
			'name' => $name ,
			'type' => $type ,
			'injection' => $code,
			'admin' => $admin,
			'main' => $main
		);
		$this->CI->db->insert('header_injections', $data); 
	}
		/**module_header_data
		 * Collects all plugin header information, and returns it.
		 * @param $type
		 * @return $module_header_data
		 */
	function module_header_data($type, $admin=0, $main=1) {
		$this->CI->db->where('type',$type);
		if ($main == 1) {
			$this->CI->db->where('main','1');
		}
		if ($admin == 1) {
			$this->CI->db->where('admin','1');
		}
		$query = $this->CI->db->get('header_injections');
		$i=0;
		$output = "";
		foreach ($query->result_array() as $row)
		{
			$output[$i]['name'] = $row['name'];
			$output[$i]['code'] = $row['injection'];
			$i++;
		}
		return $output;
	}
	
		/**html_tidy
		* Takes input and uses PHPTidy to clean it up - recommended for use of only a few elements at a time
		* @param $input_html, $indent="true", $no_body_tags="true", $fix="true"
		* @return $tidy_html
		*/
	function html_tidy( $input_html, $indent = "true", $no_body_tags = "true", $fix = "true" ) {
		ob_start(  );
		$tidy = new tidy;
		$config = array( 'indent' => $indent, 'output-xhtml' => true, 'wrap' => 200, 'clean' => $fix, 'show-body-only' => $no_body_tags );
		$tidy->parseString( $input_html, $config, 'utf8' );
		$tidy->cleanRepair(  );
		$input = $tidy;
		return $input;
	}
		/**generate_image
		* Takes input and generates an image from it
		* @param $input_text, $text_colour="#ffffff", $background_colour="#000000", $format="png"
		* @return Image Data
		*/
	function generate_image( $input_text, $text_colour = "#000000", $background_colour = "#ffffff", $format = "png" ) {
		// Set font size
		$font_size = 4;
		$background_colour = hex2rgb( $background_colour );
		$text_colour = hex2rgb( $text_colour );
		$ts = explode( "\n", $input_text );
		$width = 0;
		foreach ( $ts as $k => $string ) {
			//compute width
			$width = max( $width, strlen( $string ) );
		}
		// Create image width dependant on width of the string
		$width = ( imagefontwidth( $font_size ) * $width ) + 4;
		// Set height to that of the font
		$height = imagefontheight( $font_size ) * count( $ts );
		$el = imagefontheight( $font_size );
		$em = imagefontwidth( $font_size );
		// Create the image pallette
		$img = imagecreatetruecolor( $width, $height );
		// Dark red background
		$bg = imagecolorallocate( $img, $background_colour['red'], $background_colour['blue'], $background_colour['green'] );
		imagefilledrectangle( $img, 0, 0, $width, $height, $bg );
		// White font color
		$color = imagecolorallocate( $img, $text_colour['red'], $text_colour['blue'], $text_colour['green'] );
		foreach ( $ts as $k => $string ) {
			// Length of the string
			$len = strlen( $string );
			// Y-coordinate of character, X changes, Y is static
			$ypos = 0;
			// Loop through the string
			for ( $i = 0; $i < $len; $i++ ) {
				// Position of the character horizontally
				$xpos = ( $i * $em ) + 2;
				$ypos = $k * $el;
				// Draw character
				imagechar( $img, $font_size, $xpos, $ypos, $string, $color );
				// Remove character from string
				$string = substr( $string, 1 );
			}
		}
		if ( $format == "png" ) {
			// Return the image
			header( "Content-Type: image/png" );
			imagepng( $img );
		}
		if ( $format == "jpeg" || $format == "jpg" ) {
			header( 'Content-type: image/jpeg' );
			// Output the image
			imagejpeg( $img );
		}
		if ( $format == "gif" ) {
			// Output the image to browser
			header( 'Content-type: image/gif' );
			imagegif( $im );
		}
		// Remove image
		imagedestroy( $img );
	}
		/**generate_thumbnail
		* Generate a thumbnail from the specified image URL
		* @param $input_url, $w, $h, $percent=0,$constrain=1
		* @return Image Data
		*/
	function generate_thumbnail($input_url, $w=1, $h=1, $percent=0,$constrain=1){
		$img = $input_url;
		// get image size of img
		$x = @getimagesize( $img );
		// image width
		$sw = $x[0];
		// image height
		$sh = $x[1];

		if ( $percent > 0 ) {
				// calculate resized height and width if percent is defined
				$percent = $percent * 0.01;
				$w = $sw * $percent;
				$h = $sh * $percent;
		} else {
				if ( isset( $w ) and !isset( $h ) ) {
						// autocompute height if only width is set
						$h = ( 100 / ( $sw / $w ) ) * .01;
						$h = @round( $sh * $h );
				} elseif ( isset( $h ) and !isset( $w ) ) {
						// autocompute width if only height is set
						$w = ( 100 / ( $sh / $h ) ) * .01;
						$w = @round( $sw * $w );
				} elseif ( isset( $h ) and isset( $w ) and isset( $constrain ) ) {
						// get the smaller resulting image dimension if both height
						// and width are set and $constrain is also set
						$hx = ( 100 / ( $sw / $w ) ) * .01;
						$hx = @round( $sh * $hx );

						$wx = ( 100 / ( $sh / $h ) ) * .01;
						$wx = @round( $sw * $wx );

						if ( $hx < $h ) {
								$h = ( 100 / ( $sw / $w ) ) * .01;
								$h = @round( $sh * $h );
						} else {
								$w = ( 100 / ( $sh / $h ) ) * .01;
								$w = @round( $sw * $w );
						}
				}
		}
		$im = @imagecreatefromjpeg( $img ) or // Read JPEG Image
		$im = @imagecreatefrompng( $img ) or // or PNG Image
		$im = @ImageCreateFromGif ( $img )
		or // or GIF Image
		$im = false;

		if ( !$im ) {
				// We get errors from PHP's ImageCreate functions...
				// So let's echo back the contents of the actual image.
				readfile ($img);
		} else {
				// Create the resized image destination
				$thumb = @imagecreatetruecolor( $w, $h );
				// Copy from image source, resize it, and paste to image destination
				@imagecopyresampled( $thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh );
				// Output resized image
				@imagepng($thumb);
				//@imagejpeg( $thumb, NULL, 100);
				@imagedestroy($thumb);
		}
	}
		/**hex2rgb
		* Convert hex colours to RGB
		* @param $colour
		* @return $output['red'], $output['green'], $output['blue']
		*/
	function hex2rgb( $colour ) {
		if ( $colour[0] == '#' ) {
			$colour = substr( $colour, 1 );
		}
		if ( strlen( $colour ) == 6 ) {
			list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
		} elseif ( strlen( $colour ) == 3 ) {
			list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
		} else {
			return false;
		}
		$r = hexdec( $r );
		$g = hexdec( $g );
		$b = hexdec( $b );
		return array( 'red' => $r, 'green' => $g, 'blue' => $b );
	}
		/**rgb2hex
		* Convert RGB to hex colours
		* @param $input['red'], $input['green'], $input['blue']
		* @return $output_hex
		*/
	function rgb2hex( $red, $green, $blue ) {
		return sprintf( '#%02X%02X%02X', $red, $green, $blue );
	}
		/**Table2PDF
		* Convert a HTML table to a PDF
		* @param $input_table, $header, $footer
		* @return PDF Data
		*/

		/**list_pages
		* list all pages available
		* @param $before, $after
		* @return $pages
		*/
	function list_pages($before="", $after=""){
		$query = $this->CI->db->get('pages');
		$i = 0;
		foreach ($query->result_array() as $row){
			$pages[$i]['id'] = $row['id'];
			$pages[$i]['title'] = $row['title'];
			$pages[$i]['link'] = $row['link'];
			$i++;
		}
		$out = "";
		foreach ($pages as $page){
			$out .= $before.$page['title'].$after;
		}
		return $out;
	}
		/**list_page_urls
		* list the URLs of all available pages
		* @param $before, $after
		* @return $pages
		*/
	function list_page_urls($before,$after){
		$query = $this->CI->db->get('pages');
		$i = 0;
		foreach ($query->result_array() as $row){
			$pages[$i]['id'] = $row['id'];
			$pages[$i]['title'] = $row['title'];
			$pages[$i]['link'] = $row['link'];
			$i++;
		}
		$out = "";
		foreach ($pages as $page){
			$url = site_url($page['link']);
			$out .= $before.$url.$after;
		}
		return $out;
	}
		/**is_email
		* Validate an Email
		* @param $email
		* @return $result
		*/
	function is_email( $email ) {
		if ( valid_email( $email ) ) {
			return 1;
		} else {
			return 0;
		}
	}
		/**make_utf8
		* Strip non-UTF8 chararcters
		* @param $input
		* @return $utf8
		*/
	function make_utf8($input){
		return utf8_encode($input);
	}
		/**html2text
		* Convert HTML to HTML entities, so they don't run
		* @param $html
		* @return $text
		*/
	function html2text( $html ) {
		return htmlspecialchars( $html );
	}
		/**fancy_characters
		* Convert "s and -s, etc to their nicer counterparts
		* @param $input
		* @return $output
		*/
	function fancy_characters( $input ) {
		$count = 0;
		$i = 0;
		$tag = 0;
		$pre = 0;
		$input = str_split( $input );
		foreach ( $input as $char ) {
			if ( $char == "<" ) {
				$tag = 1;
			}
			//if we are inside a <pre>blah</pre>
			if ( $tag == 1 && $char == "<" && @$input[( $i + 1 )] == "p" && @$input[( $i + 2 )] == "r" && @$input[( $i + 3 )] == "e" ) {
				$pre = 1;
			}
			//if we are now outside a tag
			if ( $char == ">" ) {
				$tag = 0;
			}
			//</pre>
			if ( $char == ">" && $input[( $i - 1 )] == "e" && $input[( $i - 2 )] == "r" && $input[( $i - 3 )] == "p" && $input[( $i - 4 )] == "/" ) {
				$pre = 0;
			}
			if ( $tag == 1 || $pre == 1 ) {
				$out[] = $char;
				$i++;
				continue;
			}
			if ( $char == '"' ) {
				if ( $count == 0 ) {
					$char = "&#8220;";
					$count = 1;
				} else {
					$char = "&#8221;";
					$count = 0;
				}
			}
			if ( $char == "-" ) {
				if ( $input[( $i - 1 )] == " " && $input[( $i + 1 )] == " " ) {
					//check for spaces around the hyphen
					$char = "&mdash;";
				}
			}
			//Check for Elipsis (...)
			if ( trim( $char ) == "." ) {
				if ( @$input[( $i + 1 )] == "." && @$input[( $i + 2 )] == "." ) {
					//check for elipsis
					$char = "&#8230;";
				}
				if ( trim( $input[( $i - 1 )] ) == "." ) {
					$char = "";
				}
			}
			$out[] = $char;
			$i++;
		}
		return implode( "", $out );
	}

		/**static_dir
		* The public path to the static dir
		* @return $static_dir
		*/
	function static_dir(){
			return base_url().'static/';
		}
		/**br2newline
		* converts <br> and all variants to "\n"
		* @param $input
		* $output
		*/
	function br2newline( $input ) {
		$out = str_replace( "<br>", "\n", $input );
		$out = str_replace( "<br/>", "\n", $out );
		$out = str_replace( "<br />", "\n", $out );
		$out = str_replace( "<BR>", "\n", $out );
		$out = str_replace( "<BR/>", "\n", $out );
		$out = str_replace( "<BR />", "\n", $out );
		return $out;
	}
		/**day
		* returns the day (Monday)
		* @return $day
		*/
	function day(  ) {
		return date( 'l' );
	}
		/**day_of_month
		* returns the day of the month (1-31)
		* @return $month['number'], $month['suffix']
		*/
	function day_of_month( $epoch=null ) {
		if ($epoch == null){
			$epoch = date('U');
		}
		$number = date( 'j' );
		if ( $number[( strlen( $number ) - 1 )] == 1 ) {
			$suffix = "st";
		} elseif ( $number[( strlen( $number ) - 1 )] == 2 ) {
			$suffix = "nd";
		} elseif ( $number[( strlen( $number ) - 1 )] == 3 ) {
			$suffix = "rd";
		} else {
			$suffix = "th";
		}
		return array( "number" => $number, "suffix" => $suffix );
	}
		/**human_date
		* returns a humanised date.
		* @return date
		*/
	function human_date($epoch){
		$date = $this->day_of_month($epoch);
		
		return date( 'l ', $epoch) . $date['number'] . $date['suffix'] . date( ' F, Y', $epoch );
	}
		/**month
		* returns the month (January)
		* @return $month
		*/
	function month(  ) {
		return date( 'F' );
	}
		/**year
		* returns the year (2009)
		* @return $year
		*/
	function year(  ) {
		return date( 'Y' );
	}
		/**epoch
		* returns the epoch
		* @return $epoch
		*/
	function epoch(  ) {
		return date( 'U' );
	}
		/**underscore2space
		* converts underscores ("_") to spaces
		* @param $input
		* @return $output
		*/
	function underscore2space($input){
		return str_replace("_"," ", $input);
	}

		/**space2underscore
		* converts spaces to underscores ("_")
		* @param $input
		* @return $output
		*/
	function space2underscore($input){
		return preg_replace('/\s\s*/', '_',$input);
	}
	
		/**capitalize
		* Makes every word in the sentence capitalized
		* @param $input
		* @retrun $output
		*/ 
	function capitalize($input){
		return ucwords(strtolower($input));
	}
		/**get_modules
		* Gets all the modules that are installed on the system (apart from the defaults)
		* @param $config
		* @retrun $output
		*/ 
	function get_modules($config = array())
	{
		$CI =& get_instance();
		
		// Section for addmin links from modules
		
		// open the current directory
		$dhandle = opendir('modules');
		// define an array to hold the files
		$files = array();
		$return = "";
		if ($dhandle)
		{
			// loop through all of the files
			while (false !== ($fname = readdir($dhandle)))
			{
				// if the file is not this file, and does not start with a '.' or '..',
				// then store it for later display
				if (($fname[0] != '.'))
				{
				  // store the filename
				  $files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname;
			  }
		   }
		   // close the directory
		   closedir($dhandle);
		}
		// Now loop through the files, echoing out a new select option for each one
		$i = 0;
		foreach( $files as $fname )
		{
			if( file_exists('./modules/'.$fname.'/info.php') )				
			{
				require_once('./modules/'.$fname.'/info.php');
				$this->CI->db->where('name', $info['name']);
				$this->CI->db->limit(1);
				$query = $this->CI->db->get('module_list');
				foreach ($query->result_array() as $row)
				{
					$return[$i]['id'] = $row['id'];
					$return[$i]['name'] = $this->capitalize($row['name']);
					$return[$i]['description'] = $row['description'];
					$return[$i]['projecturl'] = ( anchor( $row['projecturl'] ) );
				}
			}       
			$i++; 
		} // foreach
		return $return;
	}
		/**unzip
		* Unzips a .zip file.
		* @param $zipfile, $extractdir
		* @retrun $output
		*/ 
	function unzip($zipfile,$extractdir){
		$this->CI->load->library('unzip');
		$config['fileName']  = $zipfile;
		$config['targetDir'] = $extractdir; 
		$this->CI->unzip->initialize($config); 
		$this->CI->unzip->unzipAll();
		$return = "";
		//display's error messages
		$return .= $this->CI->unzip->display_errors(2);
		//display's information messages
		$return .= $this->CI->unzip->display_errors(1);
		return $return;
	}
	
	function sql_import($path){
		require_once($path);
		$return = "";
		foreach ($sql_array as $command){
			if ( isset($command['create']) ){
				if ( $command['if_not_exists'] == 1 ){
					$query = "CREATE TABLE IF NOT EXISTS `" . $this->CI->db->dbprefix($command['create']) . "` " . base64_decode($command['params']);
					$return[] = "Creating Table (if it doesn't already exist) " . $this->CI->db->dbprefix($command['create']);
				} else {
					$query = "CREATE TABLE `" . $this->CI->db->dbprefix($command['create']) . "` " . base64_decode($command['params']);
					$return[] = "Creating Table " . $this->CI->db->dbprefix($command['create']);
				}
				$this->CI->db->query( $query );
				continue;
			}
			if ( isset($command['insert']) ){
				if ( $command['if_not_exists'] == 1 ){
					$query = "REPLACE INTO `" . $this->CI->db->dbprefix($command['insert']) . "` " . base64_decode($command['params']);
					$return[] = "Creating Table (if it doesn't already exist) " . $this->CI->db->dbprefix($command['insert']);
				} else {
					$query = "INSERT INTO `" . $this->CI->db->dbprefix($command['insert']) . "` " . base64_decode($command['params']);
					$return[] = "Inserting data into " . $this->CI->db->dbprefix($command['insert']);
				}
				$this->CI->db->query( $query );
				continue;
			}
			if ( isset($command['alter']) ){
				
				$query = "ALTER IGNORE TABLE `" . $this->CI->db->dbprefix($command['alter']) . "` " . base64_decode($command['params']);
				
				@$this->CI->db->query( $query );
				$return[] = "Altering data in " . $this->CI->db->dbprefix($command['alter']);
				continue;
			}
			if ( isset($command['optimize']) ){
				$this->CI->db->query( "OPTIMIZE TABLE `" . $this->CI->db->dbprefix($command['optimize']) . "` ");
				$return[] = "Optimizing " . $this->CI->db->dbprefix($command['optimize']);
				continue;
			}
		}
		return $return;
	}
	
	
	/**chmodr
	* Recursively Chmods directories.
	* @param path, chmod mode
	*/
	function chmodr($path, $filemode) {
		if (!is_dir($path))
			return @chmod($path, $filemode);

		$dh = opendir($path);
		while (($file = readdir($dh)) !== false) {
			if($file != '.' && $file != '..') {
				$fullpath = $path.'/'.$file;
				if(is_link($fullpath))
					return FALSE;
				elseif(!is_dir($fullpath) && !@chmod($fullpath, $filemode))
						return FALSE;
				elseif(!$this->chmodr($fullpath, $filemode))
					return FALSE;
			}
		}

		closedir($dh);

		if(chmod($path, $filemode))
			return TRUE;
		else
			return FALSE;
	}
	
	/**insert_smileys
	* Replaces plaintext-smileys with image-smileys.
	* @param input
	*/
	function insert_smileys($input){
		return parse_smileys($input, base_url().'static/smileys/');
	}
}
?>
